<?php
/**
 * 功能: 商品管理
 * User: 文丹
 * Date: 2019/1/4
 * Time: 16:39
 */

namespace app\index\controller;
use tests\thinkphp\library\think\langTest;
use think\Controller;
use think\Db;
import('taobao/TopSdk',EXTEND_PATH);
class Goods extends Controller{

    /**
     * TODO:商品分类
     */
    public function type(){
        $type = Db::name('goods_type')->where('parent_id',0)->order('sort asc')->select();
        if($type){
            return json(['msg'=>'请求成功！','ok'=>true,'type'=>$type]);
        }else{
            return json(['msg'=>'暂无数据！','ok'=>false]);
        }
    }
    /**
     * TODO:商品板块
     */
    public function block(){
        $block = Db::name('goods_block')->select();
        if($block){
            return json(['msg'=>'请求成功！','ok'=>true,'type'=>$block]);
        }else{
            return json(['msg'=>'暂无数据！','ok'=>false]);
        }
    }
    /**
     * TODO:首页商品展示
     */
    public function index(){
        $gt_id  = intval(input('gt_id',0));
        $limit  = 20;
        if($gt_id){
            $list = Db::name('goods')
                ->where('goods_end_time','>=',time())
                ->where('is_down',1)
                ->where('gt_id',$gt_id)
                ->field('id,goods_id,goods_title,goods_big_img,goods_price,goods_z_price,goods_q_price,member_yongjin')
                ->paginate($limit);
        }else{
            //is_choice **是否精选,1是，2否
            $list = Db::name('goods')
                ->where('goods_end_time','>=',time())
                ->where('is_down',1)
                ->where('is_choice',1)
                ->field('id,goods_id,goods_title,goods_big_img,goods_price,goods_z_price,goods_q_price,member_yongjin')
                ->paginate($limit);
        }

        if($list){
            return json(['msg'=>'请求成功！','ok'=>true,'goods'=>$list]);
        }else{
            return json(['msg'=>'暂无数据！','ok'=>false]);
        }

    }


    /**
     * TODO:首页商品分类家排序
     */
    public function distinct(){
        $gt_id  = intval(input('id'));//商品分类id;
      //  $sort   = intval(input('sort'));//0综合，1销量，2最新，3券额
       // $height = intval(input('height',1));//高低  ，1:desc ,2:asc
        $page   = intval(input('page'));//页码
        $limit  = 10;
      
        $goods = [];
        if($gt_id ==0){
            //精选
            /*$goods = Db::name('goods')
                ->where('goods_end_time','>=',time())
                ->where('is_choice',1)
                ->where('is_down',1)
                ->order('coupon_amount desc')
                ->paginate($limit);*/
            $goods = Db::name('goods')
                ->where('goods_end_time','>=',time())
                ->where('is_down',1)
                ->where('coupon_amount','>',0)
                ->order('goods_volume desc')
                ->paginate($limit);
        }else{
            $goods = Db::name('goods')
                ->where('goods_end_time','>=',time())
                ->where('is_down',1)
                ->where('gt_id',$gt_id)
                ->paginate($limit);
        }

        if($goods){
           // $result = array_slice($goods,($page-1)*$limit,$limit);
            return json(['msg'=>'请求成功！','ok'=>true,'goods'=>$goods]);
        }else{
            return json(['msg'=>'暂无数据！','ok'=>false]);
        }

    }
    ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * 商品详情
     */
    public function detail(){
        $goods_id = input('goods_id');
        $token    = trim(input('token')) ;
        $user     = model('user')->checkToken($token);
        if(empty($goods_id)){
            return json(['msg'=>'goods_id不能为空！','ok'=>false]);
        }
        $detail = Db::name('goods')->where('goods_id',$goods_id)->select();
       /* dump($detail);
        die;*/
        $arr = [];

        if($detail){
            foreach($detail as $k=>$v){
                $arr[$k] = $v;
                if($token){
                    $collect = Db::name('collect')->where('user_id',$user['id'])->where('goods_id',$v['goods_id'])->where('type',1)->find();

                    if($collect){
                        $arr[$k]['is_collect'] = 1;//已被收藏
                    }else{
                        $arr[$k]['is_collect'] = 0;//未收藏
                    }
                }else{
                    $arr[$k]['is_collect'] = 0;//未收藏
                }

            }
            return json(['msg'=>'请求成功','ok'=>true,'data'=>$arr]);
        }else{
            return json(['msg'=>'请求失败','ok'=>false]);
        }

    }


    /**
     * 关键词多条件 搜索
     */
    public function keySearch(){
        $gb_id     = intval(input('icon_type_id'));
        $key       = trim(input('keyword'));
        $price_min = input('price_min');//到手价格
        $price_max = input('price_max');
        $page      = intval(input('page',1));
        $limit     = 20;

        if(empty($key)&&empty($price_min)&&empty($price_max)){
            return json(['msg'=>'搜索条件不能为空','ok'=>false]);
        }
        $goods = [];

        if(!empty($key)&&empty($price_min)&&empty($price_max)){
            $goods = Db::name('goods')
                ->where('gb_id',$gb_id)
                ->where('is_down',1)
                ->where('goods_end_time','>=',time())
                ->where('goods_title','like','%'.$key.'%')
                ->paginate($limit);
        }elseif(!empty($key)&& !empty($price_min)&&empty($price_max)){
            $goods = Db::name('goods')
                ->where('gb_id',$gb_id)
                ->where('is_down',1)
                ->where('goods_end_time','>=',time())
                ->where('goods_title','like','%'.$key.'%')
                ->where('goods_z_price|goods_q_price','>=',$price_min)
                ->paginate($limit);
        }elseif(!empty($key)&& !empty($price_min)&& !empty($price_max)){
            $goods = Db::name('goods')
                ->where('gb_id',$gb_id)
                ->where('is_down',1)
                ->where('goods_end_time','>=',time())
                ->where('goods_title','like','%'.$key.'%')
                ->where('goods_z_price|goods_q_price','<=',$price_max)
                ->paginate($limit);
        }elseif(!empty($key)&& empty($price_min)&& !empty($price_max)){
            $goods = Db::name('goods')
                ->where('gb_id',$gb_id)
                ->where('is_down',1)
                ->where('goods_end_time','>=',time())
                ->where('goods_title','like','%'.$key.'%')
                ->where('goods_z_price|goods_q_price','<=',$price_max)
                ->paginate($limit);
        }elseif(empty($key)&& !empty($price_min)&& !empty($price_max)){
            $goods = Db::name('goods')
                ->where('gb_id',$gb_id)
                ->where('is_down',1)
                ->where('goods_end_time','>=',time())
                ->where('goods_title','like','%'.$key.'%')
                ->where('goods_z_price|goods_q_price','<=',$price_max)
                ->paginate($limit);
        }elseif(empty($key)&& !empty($price_min)&& empty($price_max)){
            $goods = Db::name('goods')
                ->where('gb_id',$gb_id)
                ->where('is_down',1)
                ->where('goods_end_time','>=',time())
                ->where('goods_z_price|goods_q_price','>=',$price_min)
                ->paginate($limit);
        }elseif(empty($key)&& empty($price_min)&& !empty($price_max)){
            $goods = Db::name('goods')
                ->where('gb_id',$gb_id)
                ->where('is_down',1)
                ->where('goods_end_time','>=',time())
                ->where('goods_z_price|goods_q_price','<=',$price_max)
                ->paginate($limit);
        }
        if($goods){
          //  $result = array_slice($goods,($page-1)*$limit,$limit);
            return json(['msg'=>'请求成功！','ok'=>true,'data'=>$goods]);
        }else{
            return json(['msg'=>'暂无数据！','ok'=>false]);
        }

    }

    /**
     * 商品分类搜索
     */
    public function classify_goods(){
        $gt_id = intval(input('id'));
        $gb_id = intval(input('gb_id'));
        if($gt_id<=0){
            return json(['msg'=>'id必须为正整数！','ok'=>false]);
        }
        $limit = 20;
        $list =  Db::name('goods')
            ->where('gt_id',$gt_id)
            ->where('gb_id',$gb_id)
            ->where('is_down',1)
            ->where('goods_end_time','>=',time())
            ->paginate($limit);
        if($list){
            return json(['msg'=>'请求成功！','ok'=>true,'data'=>$list]);
        }else{
            return json(['msg'=>'暂无数据！','ok'=>false]);
        }
    }
    /**
     * 商品排序
     */
    public function goods_sort(){
        /*$gt_id = intval(input('id'));*/
        $gb_id = intval(input('gb_id'));
        $sort_type  = intval(input('sort_type',1));//1综合（精品），2销量，3最新，4价格
        $sort  = trim(input('sort','asc'));//desc,asc
        $page = input('page',1);
        $limit = 20;
        $list = [];
      /*echo $sort_type;
        die;*/
        if($sort_type==1){
            $list =  Db::name('goods')
               /* ->where('gt_id',$gt_id)*/
                ->where('gb_id',$gb_id)
                ->where('is_down',1)
                ->where('goods_end_time','>=',time())
                ->where('is_choice',1)
                ->order('coupon_amount desc')
                ->paginate($limit);
        }elseif($sort_type==2){
            $list =  Db::name('goods')
               /* ->where('gt_id',$gt_id)*/
                ->where('gb_id',$gb_id)
                ->where('is_down',1)
                ->where('goods_end_time','>=',time())
                ->order('goods_volume desc')
                ->paginate($limit);
        }elseif($sort_type==3){
            $list =  Db::name('goods')
               /* ->where('gt_id',$gt_id)*/
                ->where('gb_id',$gb_id)
                ->where('is_down',1)
                ->where('goods_end_time','>=',time())
                ->order('goods_add_time desc')
                ->paginate($limit);
        }elseif($sort_type==4){
            $list =  Db::name('goods')
                /*->where('gt_id',$gt_id)*/
                ->where('gb_id',$gb_id)
                ->where('is_down',1)
                ->where('goods_end_time','>=',time())
                ->order('goods_price',$sort)
                ->paginate($limit);
        }
        if($list){
          //  $result = array_slice($list,($page-1)*$limit,$limit);
            return json(['msg'=>'请求成功！','ok'=>true,'data'=>$list]);
        }else{
            return json(['msg'=>'暂无数据！','ok'=>false]);
        }
    }


////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * TODO:浏览记录
     */
    public function browse(){
        $goods_id = trim(input('goods_id'));
        $goods_title = trim(input('goods_title'));
        $goods_big_img = trim(input('goods_big_img'));
        $goods_price = trim(input('goods_price'));
        $goods_z_price = trim(input('goods_z_price'));
        $goods_q_price = trim(input('goods_q_price'));
        $coupon_amount = trim(input('coupon_amount'));
        $goods_end_time = trim(input('goods_end_time'));
        if(empty($goods_id) ||empty($goods_title)||empty($goods_big_img)||empty($goods_price)||empty($goods_end_time)){
            return json(['msg'=>'请填写完整的数据','ok'=>false]);
        }

        $token = trim(input('token'));
        if(empty($token)){
            return json(['msg'=>'token不能为空','ok'=>false]);
        }

        $user = model('User')->getUser($token);
        $user_id = $user['id'];
        $browse = model('Browse')->getBrowse($user_id,$goods_id,$goods_end_time);
        /*echo "<pre>";
        print_r($browse);die;*/
        $data = [
            'goods_id'=>$goods_id,
            'user_id'=>$user_id,
            'goods_title'=>$goods_title,
            'goods_big_img'=>$goods_big_img,
            'goods_price'=>$goods_price,
            'goods_z_price'=>$goods_z_price,
            'goods_q_price'=>$goods_q_price,
            'coupon_amount'=>$coupon_amount,
            'goods_end_time'=>$goods_end_time,
            'time'=>time(),//浏览时间
        ];

        if(empty($browse)){
            // 启动事务
            Db::startTrans();
            try{
                model('Browse')->add($data);
                Db::name('goods')->where('goods_id',$goods_id)->setInc('browse',1,1);
                // 提交事务
                Db::commit();
                return json(['msg'=>'记录成功','ok'=>true]);
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                return json(['msg'=>'记录失败','ok'=>false]);
            }

        }else{
            $res = model('Browse')->saveBrowse($data,$user_id,$goods_id);
            if($res){
                return json(['msg'=>'更新记录成功','ok'=>true]);
            }else{
                return json(['msg'=>'更新记录失败','ok'=>false]);
            }
        }

    }
    /**
     * TODO:浏览记录展示
     */
    public function bshow(){
        $token = trim(input('token'));
        if(empty($token)){
            return json(['msg'=>'请登录！','ok'=>false]);
        }

        $user = model('User')->getUser($token);
        $user_id = $user['id'];
        $browse = model('Browse')->showBrowse($user_id);
        if($browse){
            return json(['msg'=>'请求成功','ok'=>true,'data'=>$browse]);
        }else{
            return json(['msg'=>'暂无浏览记录','ok'=>false]);
        }
    }
    /**
     * TODO:浏览记录删除
     */
    public function browse_del(){
        $id = intval(input('id'));
        $token = trim(input('token'));
        if(empty($token)){
            return json(['msg'=>'请登录！','ok'=>false]);
        }

        $user = model('User')->getUser($token);
        $user_id = $user['id'];
        if($id<=0){
            return json(['msg'=>'id必须为正整数','ok'=>false]);
        }
        $result = Db::name('browse')->where('id',$id)->where('user_id',$user_id)->delete();
        if($result){
            return json(['msg'=>'已删除','ok'=>true]);
        }else{
            return json(['msg'=>'删除失败，请稍后再试','ok'=>false]);
        }


    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /**
     * TODO:商品收藏/优惠券领取
     */
    public function collect(){
        $goods_id = trim(input('goods_id'));
        $goods_title = trim(input('goods_title'));
        $goods_big_img = trim(input('goods_big_img'));
        $goods_price = trim(input('goods_price'));
        $goods_z_price = trim(input('goods_z_price'));
        $goods_q_price = trim(input('goods_q_price'));
        $coupon_amount = trim(input('coupon_amount',0));
        $goods_end_time = trim(input('goods_end_time'));

        $member_yongjin = input('member_yongjin');//预估会员佣金
        $goods_volume = input('goods_volume');//月销量
        $goods_user_type = input('goods_user_type');//卖家类型，1表示天猫

        $type = intval(input('type'));//1商品收藏，2领取优惠券
        if(empty($goods_id) ||empty($goods_title)||empty($goods_big_img)||empty($goods_price)||empty($goods_end_time)
            ||empty($type)){
            return json(['msg'=>'请填写完整的数据','ok'=>false]);
        }

        $token = trim(input('token'));
        if(empty($token)){
            return json(['msg'=>'token不能为空','ok'=>false]);
        }

        $user = model('User')->getUser($token);
        $user_id = $user['id'];
        $check = model('Collect')->checkBrowse($user_id,$goods_id);

        if(empty($check)){
            $data = [
                'goods_id'=>$goods_id,
                'user_id'=>$user_id,
                'goods_title'=>$goods_title,
                'goods_big_img'=>$goods_big_img,
                'goods_price'=>$goods_price,
                'goods_z_price'=>$goods_z_price,
                'goods_q_price'=>$goods_q_price,
                'coupon_amount'=>$coupon_amount,
                'goods_end_time'=>$goods_end_time,
                'member_yongjin'=>$member_yongjin,
                'goods_volume'=>$goods_volume,
                'goods_user_type'=>$goods_user_type,
                'type'=>$type,
                'time'=>time()
            ];
            $result = model('Collect')->add($data);
            if($result){
                return json(['msg'=>'操作成功','ok'=>true]);
            }else{
                return json(['msg'=>'操作失败','ok'=>false]);
            }
        }else{
            return json(['msg'=>'已经操作过了','ok'=>false]);
        }
    }

    /**
     * TODO:商品收藏展示/已领优惠券展示
     */
    public function get_coll(){
        $token = trim(input('token'));
        $type  = intval(input('type'));//1商品收藏，2领取优惠券
        if(empty($token)){
            return json(['msg'=>'token不能为空','ok'=>false]);
        }

        $user = model('User')->getUser($token);
        $user_id = $user['id'];

        $collect = model('Collect')->getCollect($user_id,$type);
        if($collect){
            return json(['msg'=>'请求成功','ok'=>true,'data'=>$collect]);
        }else{
            return json(['msg'=>'暂无记录','ok'=>false]);
        }
    }
    /**
     * TODO:收藏/已领优惠券删除
     */
    public function coll_del(){
        $id = intval(input('id'));
        $goods_id = trim(input('goods_id'));
        $token = trim(input('token'));
        $user = model('User')->checkToken($token);
        if($id<=0&&empty($goods_id)){
            return json(['msg'=>'id或者goods_id不能为空','ok'=>false]);
        }
        if($id){
            $result = Db::name('collect')->where('user_id',$user['id'])->where('id',$id)->delete();
        }else{
            $result = Db::name('collect')->where('user_id',$user['id'])->where('goods_id',$goods_id)->delete();
        }

        if($result){
            return json(['msg'=>'已删除','ok'=>true]);
        }else{
            return json(['msg'=>'删除失败，请稍后再试','ok'=>false]);
        }

    }
    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * 关键字搜索
     */
    public function key_search(){
        $sort  = intval(input('sort'));//0全部，1销量，2最新，3价格
        $keyword = trim(input('keyword'));
        $height  = intval(input('height'));//
        if(empty($keyword)){
            return json(['msg'=>'搜索条件不能为空','ok'=>false]);
        }
        $page    = intval(input('page'));
        $limit   = 20;
        if($sort ==0){
            $goods  = Db::name('goods')
                ->where('is_down',1)
                ->where('goods_end_time','>=',time())
                ->where('goods_title','like','%'.$keyword.'%')
                ->order('coupon_amount desc')
                ->paginate($limit);
        }elseif($sort==1){
            $goods = Db::name('goods')
                ->where('is_down',1)
                ->where('goods_end_time','>=',time())
                ->where('goods_title','like','%'.$keyword.'%')
                ->order('goods_volume desc')
                ->paginate($limit);
        }elseif($sort==2){
                $goods = Db::name('goods')
                    ->where('is_down',1)
                    ->where('goods_end_time','>=',time())
                    ->where('goods_title','like','%'.$keyword.'%')
                    ->order('goods_add_time desc')
                    ->paginate($limit);

        }elseif($sort==3){
            if($height ==1){
                $goods = Db::name('goods')
                    ->where('is_down',1)
                    ->where('goods_end_time','>=',time())
                    ->where('goods_title','like','%'.$keyword.'%')
                    ->order('goods_price desc')
                    ->paginate($limit);
            }else{
                $goods = Db::name('goods')
                    ->where('is_down',1)
                    ->where('goods_end_time','>=',time())
                    ->where('goods_title','like','%'.$keyword.'%')
                    ->order('goods_price asc')
                    ->paginate($limit);
            }

        }


        if($goods){
           // $result = array_slice($goods,($page-1)*$limit,$limit);
            return json(['msg'=>'请求成功','ok'=>true,'data'=>$goods]);
        }else{
            return json(['msg'=>'没有符合条件的结果','ok'=>false]);
        }
    }

    /**
     * 热搜词展示
     */
    public function keyword(){
        $result = Db::name('hot_search')->where('is_down',1)->field('keyword')->select();
        if($result){
            return json(['msg'=>'请求成功','ok'=>true,'data'=>$result]);
        }else{
            return json(['msg'=>'暂无数据','ok'=>false]);
        }
    }

    /**
     * 猜你喜欢 taobao.tbk.item.recommend.get( 淘宝客商品关联推荐查询 )
     */
    public function recommend(){
        $goods_id = trim(input('goods_id'));
        $res = Db::name('goods')->where('goods_id',$goods_id)->find();
        $list = Db::name('goods')
            ->where('gt_id',$res['gt_id'])
            ->whereNotIn('id',$res['id'])
            ->order('goods_volume desc')
            ->limit(6)
            ->select();
        if($list){
            return json(['msg'=>'请求成功','ok'=>true,'data'=>$list]);
        }else{
            return json(['msg'=>'暂无数据','ok'=>false]);
        }
    }



    public function recommend_qiyon(){
        $interface = intval(input('interface'));
        //采集方式（安卓、苹果）
        if($interface==1){
            //安卓
            $appkey = config('appkeya');
            $secretKey = config('secreta');
            if(empty($appkey)||empty($secretKey)){
                return json(['msg'=>'密匙不存在！','ok'=>false]);
            }
        }else{
            //苹果
            $appkey = config('appkey');
            $secretKey = config('secret');
            if(empty($appkey)||empty($secretKey)){
                return json(['msg'=>'密匙不存在！','ok'=>false]);
            }
        }

        $goods_id = trim(input('goods_id'));
        $c = new \TopClient;
        $c->appkey = $appkey;//'24993228';
        $c->secretKey = $secretKey;//'25d49321ce26536434497403220f844f';

        $req = new \TbkItemRecommendGetRequest;
        $req->setFields("num_iid,title,pict_url,small_images,reserve_price,zk_final_price,user_type,provcity,item_url");
        $req->setNumIid($goods_id);
        $req->setCount("20");
        $req->setPlatform("1");
        $resp = $c->execute($req);

        $result =  json_decode(json_encode($resp),true);
       /* echo "<pre>";
        print_r($resp);
        die;*/
        if(isset($result['code'])){
            return  json(['msg'=>'采集器接口错误:'.$resp['msg'],'ok'=>false]);
        }
        if(!isset($result['results']['n_tbk_item'])){
            return  json(['msg'=>'采集器接口错误!']);
        }
        $goods  = $result['results']['n_tbk_item'];
        return json(['msg'=>'请求成功','ok'=>true,'data'=>$goods]);
    }

    /**
     * 商品分享 taobao.tbk.tpwd.create( 淘宝客淘口令 )
     */
    public function share(){
        $user_id   = trim(input('user_id'));//淘宝用户ID
        $text      = trim(input('text'));//口令弹框内容 长度大于5个字符
        $url       = trim(input('url'));//口令跳转目标页
        $logo      = trim(input('logo',''));//口令弹框logoURL
        if(empty($user_id)||empty($text)||empty($url)){
            return json(['msg'=>'请填写完整的数据','ok'=>false]);
        }

        //苹果
        $appkey = config('appkey');
        $secretKey = config('secret');
        if(empty($appkey)||empty($secretKey)){
            return json(['msg'=>'密匙不存在！','ok'=>false]);
        }

        $c = new \TopClient;
        $c->appkey = $appkey;
        $c->secretKey = $secretKey;
        $req = new \TbkTpwdCreateRequest;
        $req->setUserId($user_id);
        $req->setText($text);
        $req->setUrl($url);
        $req->setLogo($logo);
        //$req->setExt();
        $resp = $c->execute($req);
        $result =  json_decode(json_encode($resp),true);
        /*echo "<pre>";
        print_r($result);die;*/
        return json($result);
    }

    /**
     * 实时查询订单
     */
    public function order_real(){
       // $data   =  strtotime(' 2018-08-30 17:56:43');
       // $time  = date('Y-m-d H:i:s',$data);
        $a = strtotime('-20 minute');
      //  $time  = date('Y-m-d H:i:s',$a);
        $time  = '2018-10-16 17:15:15';
        $page  = intval(input('page',1));
        $limit = 20;
        $time1 = urlencode($time);
        $vkey  = config('vkey');
        $url   = "http://apiorder.vephp.com/order?vekey=".$vkey."&start_time=".$time1."&span=1200";
        $data  = file_get_contents($url);
        $res   = json_decode($data,true,512,JSON_BIGINT_AS_STRING);
       // $a = $res['data'][0]['tk_status'];
        if(isset($res['tip'])){
            //维易过期提醒
            $content = $res['tip'];
            $res = Db::name('remind')->insert(['content'=>$content,'time'=>time()]);
        }
      //  dump(round(0,2));
      /*print_r($res);
        die;*/
        $error = isset($res['errcode'])?$res['errcode']:$res['error'];
        if($error){
            return json(['msg'=>$error,'ok'=>false]);
        }else{
            $token = trim(input('token'));
            if(empty($token)){
                return json(['msg'=>'token不能为空','ok'=>false]);
            }
            $user = model('User')->checkToken($token);
            if(empty($user)){
                return json(['msg'=>'登录被占用','ok'=>false]);
            }

            $user_id = $user['id'];
//            dump($user_id);
//            die;

            $result = $res['data'];

            $arr = $datas = [];
            $check = [];
            $i = 0;
            if(!empty($result)){
                foreach($result as $k=>$v){
                    if(strpos($v['adzone_name'],'买就省')!==false|| strpos($v['site_name'],'买就省')!==false){
                            $arr['user_id'] = Db::name('pid')->where('adzone_id',$v['adzone_id'])->value('user_id');;
                            $arr['create_time'] = $v['create_time'];
                            $arr['order_num'] = $v['trade_id'];//订单号
                            $arr['parent_order_num'] = $v['trade_parent_id'];//父订单号
                            $arr['goods_id'] = $v['num_iid'];
                            $arr['info'] = $v['item_title'];
                            $arr['shop'] = $v['seller_shop_title'];
                            $arr['nick'] = isset($v['seller_nick'])?$v['seller_nick']:'';//旺旺名
                            $arr['amount'] = $v['item_num'];
                            $arr['price'] = $v['price'];

                            //淘客订单状态，3：订单结算，12：订单付款， 13：订单失效，14：订单成功
                            if(intval($v['tk_status'])=='12'){
                                $arr['state'] = 1;
                            }elseif(intval($v['tk_status'])=='3'){
                                $arr['state'] = 2;
                            }elseif(intval($v['tk_status'])=='13'){
                                $arr['state'] = 3;
                            }elseif(intval($v['tk_status'])=='14'){
                                $arr['state'] = 4;
                            }else{
                                $arr['state'] = 0;
                            }
                            $arr['income_rate'] = $v['income_rate'];//收入比率
                            $arr['divide_tate'] = $v['commission_rate']/100;//分成比率
                            $arr['pay'] = $v['pay_price']!=0?$v['pay_price']:$v['alipay_total_price'];//实际支付金额


                            $arr['effect'] = $v['pub_share_pre_fee'];//预估收入


                            $arr['settle'] = $v['alipay_total_price']?$v['alipay_total_price']:$v['pay_price'];
                            $arr['expect'] = $v['commission'];//佣金预计收入
                            $arr['finish_time'] = isset($v['earning_time'])?$v['earning_time']:'';
                            $arr['yj_rate'] = $v['total_commission_rate'];
                            $arr['yj_sum'] = isset($v['total_commission_fee'])?$v['total_commission_fee']:(round($arr['settle'] * ($v['total_commission_rate']), 2));;//佣金

                            $arr['member_actual'] = round(($v['commission']/2)*$arr['amount'],2);//会员佣金实际收入
                          //  $arr['member_expect'] = round(($arr['amount']*$arr['yj_rate']*$arr['settle'])/2,2);//预计会员佣金
                            $arr['member_expect'] = 0;//预计会员佣金

                            $arr['subsidy_rate'] = $v['subsidy_rate'];
                            $arr['subsidy'] = isset($v['subsidy_fee'])?$v['subsidy_fee']:(round($arr['price'] * ($v['subsidy_rate']), 2));//补贴金额
                            $arr['goods_type'] = $v['auction_category'];
                            /*$arr['media_id'] = $v['site_id'];
                            $arr['media'] = $v['site_name'];*/
                            $arr['adzone_id'] = $v['adzone_id'];
                            $arr['adzone_name'] = $v['adzone_name'];

                            //订单用户添加
                            $userData = [
                                'user_id'=>$arr['user_id'],
                                'order_num'=> $arr['order_num'] ,
                                'create_time'=>time()
                            ];
                            $check_user = Db::name('user_order')->where('order_num',$arr['order_num'])->find();
                            if(empty($check_user)){
                                Db::name('user_order')->insert($userData);
                            }

                            if ($arr['state'] == 2) {
                                //订单结算
                                $user = Db::name('user')->where('id', $arr['user_id'])->find();
                                $amount = round($v['total_commission_fee'] / 2,2);
                                $a = [
                                    'user_id' => $arr['user_id'],
                                    'commission' => $amount,
                                    'time' => strtotime($arr['finish_time']),
                                    'state' => 1,//1收入，2支出
                                    'type' => 1,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                    'remark' => '订单' . $arr['order_num'] . '收入'
                                ];
                                $check_profit = Db::name('profit')
                                    ->where('user_id', $arr['user_id'])
                                    ->where('remark', '订单' . $arr['order_num'] . '收入')
                                    ->find();
                                if (empty($check_profit)) {
                                    if($amount!=0){
                                        Db::name('profit')->insert($a);
                                        Db::name('user')->where('id',$arr['user_id'])->setInc('total',$amount);
                                        Db::name('user')->where('id',$arr['user_id'])->setInc('commission',$amount);
                                    }
                                }
                                $parent_id = $user['parent_id'];
                                if($parent_id){
                                    $parent = Db::name('user')->where('id',$parent_id)->find();

                                    //合伙人
                                    $rule = Db::name('rebate_rule')->where('us_id',$parent['status'])->find();
                                    $level1 = $rule['level1']/100;
                                    $ticheng = round($amount*$level1,2);

                                    $arr1 = [
                                        'user_id' => $parent_id,
                                        'commission' => $ticheng,
                                        'time' => strtotime($arr['finish_time']),
                                        'state' => 1,//1收入，2支出
                                        'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                        'remark' => '粉丝' . $arr['user_id'] . '订单' . $arr['order_num'] . '收入'
                                    ];
                                    $check_profit = Db::name('profit')
                                        ->where('user_id', $parent_id)
                                        ->where('remark', '粉丝' . $arr['user_id'] . '订单' . $arr['order_num'] . '收入')
                                        ->find();
                                    if (empty($check_profit)) {
                                        if($ticheng){
                                            Db::name('profit')->insert($arr1);
                                            Db::name('user')->where('id',$parent_id)->setInc('total',$ticheng);
                                            Db::name('user')->where('id',$parent_id)->setInc('commission',$ticheng);
                                            Db::name('user')->where('id',$parent_id)->setInc('rebate',$ticheng);
                                        }

                                    }
                                    $grandsire = Db::name('user')->where('id',$parent['parent_id'])->find();
                                    if($grandsire){
                                        //祖籍
                                        //合伙人
                                        $rule = Db::name('rebate_rule')->where('status',$grandsire['status'])->find();
                                        $level2 = $rule['level2']/100;
                                        $t2 = round($amount*$level2,2);

                                        if($t2){
                                            $arr2 = [
                                                'user_id' => $grandsire['id'],
                                                'commission' => $t2,
                                                'time' => strtotime($arr['finish_time']),
                                                'state' => 1,//1收入，2支出
                                                'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                                'remark' => '粉丝' . $arr['user_id'] . '订单' . $arr['order_num'] . '收入'
                                            ];
                                            $check_profit = Db::name('profit')
                                                ->where('user_id', $grandsire['id'])
                                                ->where('remark', '粉丝' . $arr['user_id'] . '订单' . $arr['order_num'] . '收入')
                                                ->find();
                                            if (empty($check_profit)) {
                                                Db::name('profit')->insert($arr2);
                                                Db::name('user')->where('id',$parent_id)->setInc('total',$t2);
                                                Db::name('user')->where('id',$parent_id)->setInc('commission',$t2);
                                                Db::name('user')->where('id',$parent_id)->setInc('rebate',$t2);
                                            }
                                        }


                                    }

                                }
                            }

                        $check = Db::name('goods_order')
                            ->where('goods_id',$arr['goods_id'])
                            ->where('order_num',$arr['order_num'])
                            ->find();

                        if (empty($check)) {
                            $datas[] = $arr;
                         //   return json(['msg' => '请求成功！', 'ok' => true,'data'=>2]);
                        }else{
                         //   return json(['msg' => '请求成功！', 'ok' => true,'data'=>111]);
                            // 启动事务
                            Db::startTrans();
                            try{

                                $success = Db::name('goods_order')
                                    ->where('goods_id',$arr['goods_id'])
                                    ->where('order_num',$arr['order_num'])
                                    ->update($arr);

                                // 提交事务
                                Db::commit();
                             //   return json(['msg' => '请求成功！', 'ok' => true,'data'=>$arr]);
                            } catch (\Exception $e) {
                                // 回滚事务
                                Db::rollback();
                                $error = $e;
                              //  dump($error);
                            //    return json(['msg'=>$error,'ok'=>false]);
                            }
                        }

                    }

                }


                Db::startTrans();
                try{
                    foreach($datas as $k=>$v){
                        $check = Db::name('goods_order')
                            ->where('goods_id',$v['goods_id'])
                            ->where('order_num',$v['order_num'])
                            ->find();
                        if(empty($check)){
                            $success = Db::name('goods_order')->insertAll($datas); //批量插入数据
                        }

                    }

                     foreach($datas as $k =>$v){
                            Db::name('user_order')->insert(['order_num'=>$v['order_num'],'create_time'=>time(),'user_id'=>$user_id]);

                            if ($v['state'] = 2) {
                                //订单结算
                                $user = Db::name('user')->where('id', $user_id)->find();
                                $amount = round($v['yj_sum'] / 2,2);
                                if($amount){
                                    $arr = [
                                        'user_id' => $user_id,
                                        'commission' => $amount,
                                        'time' => strtotime($v['finish_time']),
                                        'state' => 1,//1收入，2支出
                                        'type' => 1,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                        'remark' => '订单' . $v['order_num'] . '收入'
                                    ];
                                    $check_profit = Db::name('profit')
                                        ->where('user_id', $user_id)
                                        ->where('remark', '订单' . $v['order_num'] . '收入')
                                        ->find();
                                    if (empty($check_profit)) {
                                        Db::name('profit')->insert($arr);
                                        Db::name('user')->where('id',$user_id)->setInc('total',$amount);
                                        Db::name('user')->where('id',$user_id)->setInc('commission',$amount);
                                    }
                                }

                                $parent_id = $user['parent_id'];
                                if($parent_id){
                                    $parent = Db::name('user')->where('id',$parent_id)->find();

                                    //合伙人
                                    $rule = Db::name('rebate_rule')->where('status',$parent['status'])->find();
                                    $level1 = $rule['level1']/100;
                                    $ticheng = round($amount*$level1,2);

                                    if($ticheng){
                                        $arr1 = [
                                            'user_id' => $parent_id,
                                            'commission' => $ticheng,
                                            'time' => strtotime($v['finish_time']),
                                            'state' => 1,//1收入，2支出
                                            'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                            'remark' => '粉丝' . $user_id . '订单' . $v['order_num'] . '收入'
                                        ];
                                        $check_profit = Db::name('profit')
                                            ->where('user_id', $parent_id)
                                            ->where('remark', '粉丝' . $user_id . '订单' . $v['order_num'] . '收入')
                                            ->find();
                                        if (empty($check_profit)) {
                                            Db::name('profit')->insert($arr1);
                                            Db::name('user')->where('id',$parent_id)->setInc('total',$ticheng);
                                            Db::name('user')->where('id',$parent_id)->setInc('commission',$ticheng);
                                            Db::name('user')->where('id',$parent_id)->setInc('rebate',$ticheng);
                                        }
                                    }

                                    $grandsire = Db::name('user')->where('id',$parent['parent_id'])->find();
                                    if($grandsire){
                                        //祖籍

                                        //合伙人
                                        $rule = Db::name('rebate_rule')->where('status',$grandsire['status'])->find();
                                        $level2 = $rule['level2']/100;
                                        $t2 = round($amount*$level2,2);

                                        if($t2){
                                            $arr2 = [
                                                'user_id' => $grandsire['id'],
                                                'commission' => $t2,
                                                'time' => strtotime($v['finish_time']),
                                                'state' => 1,//1收入，2支出
                                                'type' => 2,//1自己订单收入，2粉丝提成收入，3用户提现支出
                                                'remark' => '粉丝' . $user_id . '订单' . $v['order_num'] . '收入'
                                            ];
                                            $check_profit = Db::name('profit')
                                                ->where('user_id', $grandsire['id'])
                                                ->where('remark', '粉丝' . $user_id . '订单' . $v['order_num'] . '收入')
                                                ->find();
                                            if (empty($check_profit)) {
                                                Db::name('profit')->insert($arr2);
                                                Db::name('user')->where('id',$parent_id)->setInc('total',$t2);
                                                Db::name('user')->where('id',$parent_id)->setInc('commission',$t2);
                                                Db::name('user')->where('id',$parent_id)->setInc('rebate',$t2);
                                            }
                                        }


                                    }
                                }

                            }

                        }

                    // 提交事务
                    Db::commit();
                  //  return json(['msg'=>"请求成功",'ok'=>true,'data'=>$list]);
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $error = $e->getMessage();
                  //  return json(['msg'=>$error,'ok'=>false]);
                }

            }


        }


    }

    /**
     * 获取淘客商品详情所有信息（详情版）
     */
    public function getdetail(){
        $goods_id = input('goods_id');
        $str = '"itemNumId":"'.$goods_id.'"';
        /*dump($str);
        die;*/
        $arr = urlencode($str);
        $dd = 'https://acs.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/?data={%22itemNumId%22%3A%22578634668206%22}';
        $url = 'https://acs.m.taobao.com/h5/mtop.taobao.detail.getdetail/6.0/?data={'.$arr.'}';
       // $url = 'https://hws.m.taobao.com/cache/mtop.wdetail.getItemDescx/4.1/?data='.$arr.'&type=jsonp&dataType=jsonp';

        $data  = file_get_contents($url);
       // dump($data);

        /*$a = ltrim($data,'callback(');
        $b = rtrim($a,')');*/
        $result =  json_decode($data,true);
        /*echo "<pre>";
        print_r ($result);

        die;*/
       return $data;

    }

    /**
     * 热销榜 - 维易接口数据
     */
    public function hot_sade(){
        $goods_add_time = Db::name('goods')->where('gb_id',10)->order('goods_add_time desc')->value('goods_add_time');

        $str1 = date("Y-m-d",$goods_add_time)." 0:0:0";
       // $data["star"] = strtotime($str1);
        $str=date("Y-m-d",$goods_add_time)." 23:59:59";
      //  $data["end"]=strtotime($str);
     /*   dump($str1);
        dump($str);
die;*/
        $res = Db::name('goods')->where('gb_id',10)
            ->whereTime('goods_add_time','>=',$str1)
            ->whereTime('goods_add_time','<=',$str)
            ->paginate(20);
        if($res){
            return json(['msg'=>'请求成功！','ok'=>true,'data'=>$res]);
        }else{
            return json(['msg'=>'暂无数据！','ok'=>false]);
        }
    }

    /**
     * 生成微信二维码发单图接口
     */
   public function tt($url,$rand){

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);

        $file = curl_exec($ch);

        curl_close($ch);


        $timeFile = date('Ymd',time()); // 按照时间生成目录
        $pic1 = $rand.substr(md5(time()),5,10).'.jpg';
        $pic =  ROOT_PATH.'public/files/'.$timeFile;
        $path1 = $pic .'/'.$pic1;
        $path   = $timeFile.'/'.$pic1;
        if(!is_dir($pic)){
            $r = mkdir($pic,0777,true);
            chmod($pic,0777);
            if(!$r){
                return json(['msg'=>'创建目录失败！','ok'=>false]);
            }
        }

     //   $filename = pathinfo($path1, PATHINFO_BASENAME);

        $resource = fopen($path1 , 'a');

        fwrite($resource, $file);

        fclose($resource);
        return $path;

    }

    public function share_er(){
        $token = trim(input('token'));
        $id = Db::name('user')->where('token',$token)->value('id');
        $pid = Db::name('pid')->where('user_id',$id)->value('adzone_pid');
        if(empty($id)){
            return json(['msg'=>'你等登录被占用！','ok'=>false]);
        }
        if(empty($pid)){
            return json(['msg'=>'或者pid数量不足，没有分配pid','ok'=>false]);
        }
        $vkey  = config('vkey');
        $para = trim(input('para'));

        $check = Db::name('share')
            ->where('user_id',$id)
            ->where('para',$para)
            ->find();
        if($check){
            return json(['msg'=>'请求成功！','ok'=>true,'data'=>$check]);
        }else{
            $url = "http://api.vephp.com/qrpic?vekey=".$vkey."&para=".$para."&pid=".$pid;
            $data  = file_get_contents($url);
            $res   = json_decode($data,true);

            $a = $res['pic'];
            $rand      = getRandomString(1);
            $rand1     = $rand.'p';

            $pic = $this->tt($a,$rand1);

            $data = [
                'user_id'=>$id,
                'para'=>$para,
                'pic'=>$pic,
                'picy'=> $res['pic'],
                'copy_tkl_url'=>$res['copy_tkl_url'],
            ];
            Db::name('share')->insert($data);
            return json(['msg'=>'请求成功！','ok'=>true,'data'=>$data]);
        }

    }

    /**
     * 二维码发单图删除
     */
    public function del_er(){
        $token = trim(input('token'));
        $id = Db::name('user')->where('token',$token)->value('id');
        if(empty($id)){
            return json(['msg'=>'你等登录被占用！','ok'=>false]);
        }
        $para = trim(input('para'));
        $res = Db::name('share')->where('user_id',$id)->where('para',$para)->delete();
       if($res){
           return json(['msg'=>'已删除！','ok'=>true]);
       }else{
           return json(['msg'=>'删除失败！','ok'=>false]);
       }
    }

    /**
     * 维易超级搜索接口
     */
    public function super(){
        $keyword = trim(input('para'));
        $vekey   = config('vkey');
        $page    = intval(input('page',1));
        $coupon  = intval(input('coupon',0));
        $sort    = trim(input('sort'));
        /**
         *  tk_rate_des（淘客佣金比率降序）,
         *  total_sales_des（销量降序）,
         *  price_des（价格降序）,
         *  price_asc（价格升序）;
         */
      if($coupon){
          $url = "http://apis.vephp.com/super?vekey=".$vekey."&para=".$keyword."&page=".$page."&sort=".$sort."&coupon=1";
      }else{
          $url = "http://apis.vephp.com/super?vekey=".$vekey."&para=".$keyword."&page=".$page."&sort=".$sort;
      }


        $data    = file_get_contents($url);
        $res     = json_decode($data,true);
       /* dump($res);
        die;*/
        if(isset($res['error'])&&$res['error']!=0){
            return json(['msg'=>$res['msg'],'ok'=>false]);
        }
        $arr = $res['result_list'];
       /* echo "<pre>";
        dump($arr);
        die;*/
        $list = [];
        foreach($arr as $v){
            if( empty( $v['num_iid'])){
                $list[0] =  $arr;
            }else{
                $list = $arr;
            }
        }

        if($list){
            $datas = $data = [];
            $data2 = $data = [];
            foreach($list as $v){

                $data['goods_add_time'] = time();
                $data['goods_id'] = $v['num_iid']?$v['num_iid']:'';//商品ID
                $data['goods_title'] = $v['title']?$v['title']:'';//标题
                $data['goods_big_img'] = $v['pict_url']?$v['pict_url']:'';//大图地址
                $data['goods_small_img'] = isset($v['small_images'])?json_encode($v['small_images']):'';
                $data['goods_detail_url'] = $v['item_url']?$v['item_url']:$v['url'];//商品详情地址
                $data['goods_volume'] = $v['volume']?$v['volume']:0;//月销量
                $data['goods_seller_id'] = $v['seller_id']?$v['seller_id']:'';//供应商ID，卖方id
                $data['goods_nick'] = isset($v['nick'])?$v['nick']:'';//掌柜旺旺名
                $data['goods_price'] = isset($v['reserve_price'])?$v['reserve_price']:$v['zk_final_price'];//商品价格
                $data['goods_z_price'] = $v['zk_final_price']?$v['zk_final_price']:$data['goods_price'];//折后价
                $data['goods_shop_title'] = $v['shop_title']?$v['shop_title']:'';//店铺名称

                $time = intval(time()+72*86400);
                $data['goods_end_time'] = isset($v['coupon_end_time'])?strtotime($v['coupon_end_time']):$time;

                if(!empty($v['coupon_info'])){

                    $data['goods_q_price'] = $data['goods_z_price'] - get_word($v['coupon_info'], '减', '元');//券后价格
                    $data['state'] = 1;
                    $data['coupon_id']   = isset($v['coupon_id'])?$v['coupon_id']:'';

                    $data['coupon_info'] = $v['coupon_info'];
                    $data['coupon_end_time'] = isset($v['coupon_end_time'])?$v['coupon_end_time']:0;//优惠券结束时间
                    $data['coupon_start_time'] = isset($v['coupon_start_time'])?$v['coupon_start_time']:0;//优惠券开始时间
                    $data['coupon_total_count'] = isset($v['coupon_total_count'])?$v['coupon_total_count']:0;//优惠券结总数
                    $data['coupon_remain_count'] = isset($v['coupon_remain_count'])?$v['coupon_remain_count']:0;//优惠券剩余量
                    $data['coupon_amount'] = get_word($v['coupon_info'], '减', '元');
                    $data['coupon_click_url'] = isset($v['coupon_share_url'])?$v['coupon_share_url']:(isset($v['coupon_click_url'])?$v['coupon_click_url']:'');//优惠券链接地址//推广链接

                }else{
                    $data['goods_q_price'] = $data['goods_price'];
                    $data['state'] = 0;
                    $data['coupon_id']   = '';
                    $data['coupon_info'] = '';
                    $data['coupon_end_time'] = 0;//优惠券结束时间
                    $data['coupon_start_time'] = 0;//优惠券开始时间
                    $data['coupon_total_count'] = 0;//优惠券结总数
                    $data['coupon_remain_count'] = 0;//优惠券剩余量
                    $data['coupon_amount'] = 0;
                    $data['coupon_click_url'] = '';//优惠券链接地址//推广链接
                }
                $data['goods_yj_rate'] = $v['commission_rate'];//佣金比例
                if($data['goods_price']!=0 && $data['goods_z_price']!=0 && $data['goods_q_price']!=0){
                    $min = min($data['goods_price'],$data['goods_z_price'],$data['goods_q_price']);
                   $data['goods_yongjin'] = round($min* ($v['commission_rate']/10000), 1);//佣金
                //    $data['goods_yongjin'] = round($min* ($v['commission_rate']/100), 1);//佣金
                    $data['member_yongjin'] = $data['goods_yongjin']/2;//会员佣金
                }else{
                    $data['goods_yongjin'] = round($data['goods_price']* ($v['commission_rate']/10000), 1);//佣金
                  //  $data['goods_yongjin'] = round($data['goods_price']* ($v['commission_rate']/100), 1);//佣金
                    $data['member_yongjin'] = $data['goods_yongjin']/2;//会员佣金
                }
                $data['goods_city'] = isset($v['provcity'])?$v['provcity']:'';//商品所在城市
                $data['goods_user_type'] = $v['user_type'];//卖家类型,1表示天猫

                $check_repeat = Db::name('goods')->where('goods_id',$data['goods_id'])->find();//检查重复
                //  print_r($check_repeat);

                if(empty($check_repeat)){
                    if(count($data)==28){
                        $data2[] = $data;
                        $datas[] = $data;
                    }

                }else{
                    $data2[] = $data;
                   Db::name('goods')->where('goods_id','=',$data['goods_id'])->update($data);
                }


            }


            // 去除goods_id 相同的数组
            $tmp_arr = array();
            foreach($datas as $key=>$value){
                $tmp_arr[$key] = $value;
            }
            $res = second_array_unique_bykey($tmp_arr,'goods_id');

            if(!empty($res)){
                $success = Db::name('goods')->insertAll($res);
                return json(['msg'=>'请求成功','ok'=>true,'data'=>$data2]);
            }else{
                return json(['msg'=>'搜索成功！','ok'=>true,'data'=>$data2]);
            }
        }

    }


}